
//
//  ViewFromXib.swift
//  SwiftStudy
//
//  Created by apple on 16/12/26.
//  Copyright © 2016年 com.zaoguankeji.www. All rights reserved.
//

import Foundation

import UIKit

///MARK : -- How to Initialise a UIView Class with a XIB file in swift

extension Bundle {
    
    static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
        if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
            return view
        }
        
        fatalError("Could not load view with type " + String(describing: type))
    }
}

extension UIView {
    
    class func loadViewFromNibNamed(_ nibNamed: String, bundle: Bundle? = nil) -> UIView?{
    
    return UINib(nibName: nibNamed, bundle: bundle).instantiate(withOwner: self, options: nil).first as? UIView
    }
}

protocol UIViewLoading {}
extension UIView : UIViewLoading {}
extension UIViewLoading where Self : UIView {
    // note that this method returns an instance of type `Self`, rather than UIView
    static func loadFromNib() -> Self {
        let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
        let nib = UINib(nibName: nibName, bundle: nil)
        return nib.instantiate(withOwner: self, options: nil).first as! Self
   }
}
